package com.cloud.common.baseHandler;

import com.cloud.common.response.CodeEnum;
import com.cloud.common.response.ProException;
import com.cloud.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = ProException.class)
    @ResponseBody
    public Result proExceptionHandler(HttpServletRequest req, ProException e){
        //这里还可以进行一些其他操作，比如日志记录等
        log.error(e.getMessage());
        return Result.error(null,e.getErrorCode(),e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error(e.getMessage());
        Result result = new Result();
        result.setCode(CodeEnum.BODY_NOT_MATCH.getResultCode());
        result.setMessage(CodeEnum.BODY_NOT_MATCH.getResultMsg());
        result.setStatus(false);
        return result;
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<Object> MethodArgumentNotValidExceptionHandler(BindException e) {
        log.error(e.getMessage());
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        return Result.error(CodeEnum.BODY_NOT_MATCH.getResultCode(), objectError.getDefaultMessage());
    }

    /**
     * 还可以添加一些其他类型的异常
     */

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, Exception e){
        log.error(e.getMessage());
        Result result = new Result();
        result.setCode(CodeEnum.INTERNAL_SERVER_ERROR.getResultCode());
        result.setMessage(CodeEnum.INTERNAL_SERVER_ERROR.getResultMsg());
        result.setStatus(false);
        return result;
    }
}
